<!DOCTYPE html>
<html lang="zh-CN">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>判断数字并计算累加和</title>
  <style>
    body {
      font-family: Arial, sans-serif;
    }

    label {
      display: block;
      margin-top: 10px;
    }

    input {
      margin-bottom: 10px;
    }
  </style>
</head>

<body>
  <h2>判断输入是否为数字并计算累加和</h2>
  <label for="inputNumber">请输入一个数：</label>
  <input type="text" id="inputNumber">
  <button onclick="calculateSum()">计算累加和</button>
  <div id="result"></div>

  <script>
    function calculateSum() {
      const inputValue = document.getElementById('inputNumber').value;
      // 判断输入是否为有效的数字
      if (!isNaN(parseFloat(inputValue)) && isFinite(inputValue)) {
        const num = parseInt(inputValue);
        let sum = 0;
        for (let i = 1; i <= num; i++) {
          sum += i;
        }
        document.getElementById('result').innerHTML = `从 1 加到 ${num} 的和是：${sum}`;
      } else {
        document.getElementById('result').innerHTML = '请输入有效的数字';
      }
    }
  </script>
</body>

</html>